use std::ops::Deref;

use gloo::utils::window;
use log::info;
use web_sys::{Event, HtmlInputElement};
use yew::events::MouseEvent;
use yew::prelude::*;
use yew_router::prelude::*;

// route
use crate::routes::route::Route;
// mod
mod components;

use components::model::LoginForm;

#[function_component]
pub fn App() -> Html {
    let name = use_state(|| "admin".to_string());
    let password = use_state(|| "".to_string());
    let is_valid = use_state(|| false);
    // 路由
    let navigator = use_navigator().unwrap();

    //
    let handle_login_submit = {
        let name = name.clone();
        let password = password.clone();
        let is_valid = is_valid.clone();
        Callback::from(move |event: MouseEvent| {
            event.stop_propagation();
            event.prevent_default();
            let form: LoginForm = LoginForm {
                name: name.deref().to_string(),
                password: password.deref().to_string(),
            };

            if form.name.ne("admin") || form.password.ne("admin123") {
                // ..
                is_valid.set(true);
                window().alert_with_message("用户名或密码错误!").unwrap();
                return;
            }
            // panic!("login from -----{:#?}", form);
            info!("login form ---{:#?}", form);
            // 跳转路由到首页
            navigator.push(&Route::Main);
        })
    };

    //
    let update_name = {
        let name = name.clone();
        Callback::from(move |event: Event| {
            let input = event.target_dyn_into::<HtmlInputElement>();
            if let Some(input) = input {
                name.set(input.value())
            }
        })
    };
    let update_password = {
        let password: UseStateHandle<String> = password.clone();
        Callback::from(move |event: Event| {
            // ...
            let input = event.target_dyn_into::<HtmlInputElement>();
            if let Some(input) = input {
                password.set(input.value())
            }
        })
    };

    return html! {
        <div class="login">
            <div class="login-bg">
                <img src={"/hboot/public/image/login-work.png"} />
            </div>
            <div class="login-form">
                <h2>{"yew-web"}</h2>
                <form class="hb-form" id={"form"}>
                    <input class="hb-input" value={name.clone().deref().to_string()} onchange={update_name} required={true} name={"name"} type={"text"} placeholder={"用户名"} />
                    <input class="hb-input" value={password.clone().deref().to_string()}  onchange={update_password} required={true} name={"password"} type={"password"} placeholder={"密码"} />

                    <button class="hb-button" onclick={handle_login_submit} type="submit">{"登录"}</button>
                </form>
                <p class="tip">{"测试密码：admin123"}</p>
            </div>

        </div>
    };
}
